import {
	defineStore
} from 'pinia';
export const useCartStore = defineStore('cart', {
	state: () => {
		return {
			list: [{
					checked: false, //是否选中
					id: 11,
					title: "商品标题111",
					cover: "/static/images/demo/list/1.jpg",
					pprice: 200,
					num: 1, //当前的值
					skusText: '绿色、标配',
					minnum: 1,
					maxnum: 10, // 该商品最大商品数，跟库存有关
				},
				{
					checked: false, //是否选中
					id: 12,
					title: "商品标题222",
					cover: "/static/images/demo/list/3.jpg",
					pprice: 200,
					num: 2, //当前的值
					skusText: '红色、标配',
					minnum: 1,
					maxnum: 10, // 该商品最大商品数，跟库存有关
				},
				{
					checked: false, //是否选中
					id: 13,
					title: "商品标题333",
					cover: "/static/images/demo/list/2.jpg",
					pprice: 200,
					num: 3, //当前的值
					skusText: '绿色、高配',
					minnum: 1,
					maxnum: 10, // 该商品最大商品数，跟库存有关
				}
			],
			selectedAll: [] //放所有选中列表的id
		};
	},

	getters: {
		//购物车为空
		isListShow(){
			return this.list.length == 0
		},
		//全选
		checkedAll() {
			return this.selectedAll.length == this.list.length;
		},
		totalPrice() {
			let total = 0;
			this.list.map(v => {
				if (v.checked) {
                  total += v.pprice*v.num 
				}
			})
			return total
		}
	},
	actions: {
		//删除
		delSelect(){
			this.list = this.list.filter(v=>{
				return !v.checked
			})
			this.selectedAll = []
		},
		//单选
		selectItem(payload) {
			console.log('payload', payload);
			if (this.list[payload].checked) {
				this.list[payload].checked = false;
				let index = this.selectedAll.indexOf(this.list[payload].id)
				this.selectedAll.splice(index, 1)
			} else {
				this.list[payload].checked = true;
				this.selectedAll.push(this.list[payload].id)
			}
			// 一开始有没有选中
			// 如一开始是选中,那便变为不选中,selectedAll里面的id拿出来
			// 如一开始是不选中,那便变为选中,selectedAll里面放入id
			console.log('this.selectedAll', this.selectedAll);
		},

		//全选
		selectAll() {
			// 1.让所有的checked变成true
			// 2.selectedAll所有的id都在在里面
			this.selectedAll = this.list.map(item => {
				item.checked = true
				return item.id
			})
		},
		//全不选
		unselectAll() {
			this.list.map(item => {
				item.checked = false
			})
			this.selectedAll = []
		},
		doSelect() {
			this.checkedAll ? this.unselectAll() : this.selectAll()
		}
	},
});